package com.daiqee.service.impl;

import java.io.IOException;

import java.net.URISyntaxException;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.daiqee.pojo.AccountInfo;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.daiqee.dao.mapper.AccountInfoMapper;
import com.daiqee.service.httpclient.HttpClientService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 账户信息
 * 
 * <br/>
 * @since JDK 1.8
 * @version  V2.1
 * @author RichardTang 
 * @date: 2018年5月8日 上午8:21:28
 * @package com.daiqee.service.impl
 * @copyright:Copyright (c) 2018, 1245811923@qq.com All Rights Reserved.
 */
@Service
public class AccountInfoService extends ServiceImpl<AccountInfoMapper, AccountInfo>{
	
	@Value("${card.api}")
	private String cardInfoApiUrl;

	@Autowired(required = false)
	private HttpClientService httpclient;
	
	@Autowired
	private AccountInfoMapper accountInfoMapper;
	
	ObjectMapper mapper = new ObjectMapper();
	
	/**
	 * 添加账户信息
	 * @see com.daiqee.service.IAccountInfoService#addAccountInfo(com.daiqee.pojo.AccountInfo)
	 * 
	 * @param account
	 * 			账户信息
	 * 
	 * @return boolean
	 * @throws IOException 
	 * @throws URISyntaxException 
	 * @throws ClientProtocolException 
	 */
	public Boolean addAccountInfo(AccountInfo account) throws Exception {
		
		//先通过银行卡号查询相关信息
		Map<String,Object> params = new LinkedHashMap<String,Object>();
		
		//设置查询条件6217002710000684874
		params.put("inputValue",account.getAccountInfoCardNumber());
		params.put("limit", "10");
		params.put("offset", "1");
		params.put("sortOrder", "asc");
		
		//查询
		String doPost = httpclient.doPost(cardInfoApiUrl, params);
		
		//解析json
		JsonNode readTree = mapper.readTree(doPost);
		
		//获取rows节点
		JsonNode rowsNode = readTree.get("rows").get(0);
		
		if(rowsNode != null && !(rowsNode.toString().equals("null"))) {
			
			//所属银行
			account.setAccountInfoBank(rowsNode.get("orgName").toString().replaceAll("[^\\u4e00-\\u9fa5]", ""));
			
			//银行卡名称
			account.setAccountInfoCardName(rowsNode.get("cardName").toString().replace("\"", ""));
			
			//银行卡类型
			account.setAccountInfoCardType(rowsNode.get("cardType").toString().replace("\"", ""));
			
		}else {
			account.setAccountInfoBank("未知所属银行!");
			account.setAccountInfoCardName("未知卡名称!");
			account.setAccountInfoCardType("未知卡类型!");
		}
		
		return accountInfoMapper.insert(account) > 0 ? true : false;
	}
	
}
